import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { allAsyncRoutes, constantRoutes } from "@/router/routes";
import { cloneDeep } from "lodash";
import router from "@/router";

// 获取异步路由
function getAsyncRoutes(allAsyncRoutes, routeNames) {
  return allAsyncRoutes.filter((route) => {
    // 如果有子路由, 先对子路由进行过滤处理
    if (route.children && route.children.length > 0) {
      // 递归调用得到有权限的子路由的数组, 并赋给children
      route.children = getAsyncRoutes(route.children, routeNames);
    }
    // 如果当前路由的标识在路由权限数组中, 当前路由就是当前用户的权限路由
    return routeNames.includes(route.name);
  });
}
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    buttons: [],
    routes: [],
  };
};

const state = getDefaultState();
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    setToken(token);
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USER: (state, { roles, buttons, routes }) => {
    state.roles = roles;
    state.buttons = buttons;
    state.routes = routes;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((response) => {
          localStorage.setItem(
            "userType",
            response.data.loginUser.user.userType
          );
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response;
          const filterRoutes = getAsyncRoutes(
            cloneDeep(allAsyncRoutes),
            data.routes
          );
          router.addRoutes(filterRoutes);
          // if (!data) {
          //   return reject('Verification failed, please Login again.')
          // }
          const { name, avatar, roles, buttons } = data;
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_USER", {
            roles,
            buttons,
            routes: [...constantRoutes, ...filterRoutes],
          });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};
// 添加映射信息
// console.log(filterRoutes)
// router.addRoutes([...allAsyncRoutes, anyRoutes])

// router.addRoutes(anyRoutes)

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
